import 'dart:async';

import 'package:flutter/material.dart';
import 'package:jd_flutter/base/foundation/flutter_extension.dart';
import 'package:jd_flutter/base/foundation/jd_colors.dart';
import 'package:jd_flutter/base/router/router_util.dart';
import 'package:jd_flutter/base/widget/basic/base_gesture.dart';
import 'package:jd_flutter/base/widget/basic/jd_app_bar.dart';
import 'package:jd_flutter/base/widget/ui/jd_button.dart';
import 'package:jd_flutter/modules/pages/login/code/verification_box.dart';
import 'package:jd_flutter/modules/pages/login/code/verification_box_item.dart';
import 'package:jd_flutter/modules/router/router_contract_page.dart';

import 'login_tool.dart';

// 输入验证码
class LoginCodePage extends StatefulWidget {
  final Map<String, dynamic> params;
  const LoginCodePage({Key? key, required this.params}) : super(key: key);
  get phoneNo => params.getStringNotNull('phoneNo');

  @override
  State<LoginCodePage> createState() => _LoginCodePageState();
}

class _LoginCodePageState extends State<LoginCodePage> {
  /// 倒计时秒数
  final int totalLeftSecond = 60;

  /// 当前秒数
  late int currentSecond = 60;
  //是否倒计时中
  bool isCountingDown = true;
  //发送验证码按钮是否可以点击
  bool sendBtnClickable = false;

  StreamSubscription<dynamic>? _subscription;

  @override
  void initState() {
    super.initState();
    startTimer();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: false,
      appBar: JDAppBar(
        actionWidgets: const [],
      ),
      body: DismissKeyBord(
          child: Container(
        padding: const EdgeInsets.fromLTRB(36, 10, 36, 10),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            50.vGap,
            const Center(
              child: Text(
                "验证码登录",
                style: TextStyle(
                    color: JDColors.c222222,
                    fontSize: 27.0,
                    fontWeight: FontWeight.bold),
              ),
            ),
            8.vGap,
            Center(
              child: Text(
                '验证码已发送至${widget.phoneNo}',
                style: const TextStyle(color: JDColors.c999999, fontSize: 12),
              ),
            ),
            49.vGap,
            SizedBox(
              height: 54,
              child: VerificationBox(
                showCursor: true,
                borderRadius: 18,
                cursorWidth: 2,
                cursorColor: const Color(0xFFF6C113),
                type: VerificationBoxItemType.box,
                onSubmitted: (str) {
                  goToLogin(str);
                },
              ),
            ),
            54.vGap,
            Center(
              child: JDButton(
                key: const Key('getVerificationCode'),
                minWidth: context.width - 72,
                minHeight: 54,
                radius: 54 / 2,
                onPressed: (sendBtnClickable) ? requestCode : null,
                textStyle: sendBtnClickable
                    ? const TextStyle(color: Color(0xFFFFFFFF), fontSize: 15)
                    : const TextStyle(color: Color(0xFFFFFFFF), fontSize: 15),
                text: sendBtnClickable ? "获取验证码" : '$currentSecond 秒后可重新发送',
              ),
            ),
          ],
        ),
      )),
    );
  }

  goToLogin(String code) async {
    // Map<String, dynamic> map =
    //     await JDApiRequest.post('xxxx')
    //         .params({'mobile': widget.phoneNo, 'code': code})
    //         .needToastError(true)
    //         .loadListener(JDApiRequest.defaultListener)
    //         .request;
    //
    // jdLog('登录结果 map---> $map');
    // if (map.responseSucceed()) {
    // }
    jump();
  }

  jump() {
    LoginTool.loginIn({});

    Future.delayed(Duration.zero, () {
      RouterUtil.popUntil(context);
      RouterContractPage.instance.tabNavigator
          .push(context, replacement: true, hideAnimation: true);
    });
  }

  //发送验证码
  requestCode() async {
    setState(() {
      sendBtnClickable = false;
      currentSecond = totalLeftSecond;
    });
    // Map map = await JDApiRequest.post('xxx')
    //     .params({'action': 'register', 'mobile': widget.phoneNo})
    //     .needToastError(true)
    //     .loadListener(JDApiRequest.defaultListener)
    //     .request;
    // if (map.responseSucceed()) {
    //   startTimer();
    // } else {
    //   setState(() {
    //     sendBtnClickable = true;
    //   });
    // }
    startTimer();
  }

  startTimer() {
    _subscription?.cancel();
    isCountingDown == true;
    _subscription = Stream.periodic(const Duration(seconds: 1), (int i) => i)
        .take(totalLeftSecond)
        .listen((int i) {
      setState(() {
        currentSecond = totalLeftSecond - i - 1;
        if (currentSecond < 0) {
          currentSecond = 0;
        }
        sendBtnClickable = currentSecond < 1;
        if (sendBtnClickable && isCountingDown == true) {
          isCountingDown = false;
          _subscription?.cancel();
        }
      });
    });
  }

  @override
  void dispose() {
    _subscription?.cancel();
    super.dispose();
  }
}
